import json
import logging
from typing import Dict, Any
from cryptography.fernet import Fernet
from cryptography.hazmat.primitives import hashes
from config import FERNET_KEY

logger = logging.getLogger(__name__)

class EncryptionHandler:
    def __init__(self):
        self.cipher_suite = Fernet(FERNET_KEY)
        
    def encrypt_data(self, data: Dict[str, Any]) -> bytes:
        """加密数据"""
        try:
            if not isinstance(data, dict):
                raise TypeError("数据必须是字典类型")
                
            data_bytes = json.dumps(data).encode()
            return self.cipher_suite.encrypt(data_bytes)
        except Exception as e:
            logger.error(f"加密数据失败: {str(e)}")
            raise
            
    def decrypt_data(self, encrypted_data: bytes) -> Dict[str, Any]:
        """解密数据"""
        try:
            decrypted_bytes = self.cipher_suite.decrypt(encrypted_data)
            return json.loads(decrypted_bytes)
        except Exception as e:
            logger.error(f"解密数据失败: {str(e)}")
            raise
            
    def hash_metadata(self, metadata: Dict[str, Any]) -> bytes:
        """生成元数据哈希"""
        try:
            metadata_str = json.dumps(metadata, sort_keys=True)
            digest = hashes.Hash(hashes.SHA256())
            digest.update(metadata_str.encode())
            return digest.finalize()
        except Exception as e:
            logger.error(f"生成元数据哈希失败: {str(e)}")
            raise 